//
//  ImageUtils.swift
//  puretennis
//
//  Created by IYE Technologies on 11/25/14.
//  Copyright (c) 2014 IYE Technologies. All rights reserved.
//

import Foundation
import UIKit
import ImageIO

class ImageUtils {
    class func RBSquareImageTo(image: UIImage, size: CGSize) -> UIImage {
        return RBResizeImage(RBSquareImage(image), targetSize: size)
    }
    
    class func RBSquareImage(image: UIImage) -> UIImage {
        var originalWidth = image.size.width
        var originalHeight = image.size.height
        var edge: CGFloat
        if originalWidth > originalHeight {
            edge = originalHeight
        } else {
            edge = originalWidth
        }
        var posX = (originalWidth - edge) / 2.0
        var posY = (originalHeight - edge) / 2.0
        var cropSquare = CGRectMake(posX, posY, edge, edge)
        var imageRef = CGImageCreateWithImageInRect(image.CGImage, cropSquare);
        return UIImage(CGImage: imageRef, scale: UIScreen.mainScreen().scale, orientation: image.imageOrientation)!
    }
    
    class func RBResizeImage(image: UIImage, targetSize: CGSize) -> UIImage {
        let size = image.size
        let widthRatio = targetSize.width / image.size.width
        let heightRatio = targetSize.height / image.size.height
        // Figure out what our orientation is, and use that to form the rectangle
        var newSize: CGSize
        if(widthRatio > heightRatio) {
            newSize = CGSizeMake(size.width * heightRatio, size.height * heightRatio)
        } else {
            newSize = CGSizeMake(size.width * widthRatio, size.height * widthRatio)
        }
        // This is the rect that we've calculated out and this is what is actually used below
        let rect = CGRectMake(0, 0, newSize.width, newSize.height)
        // Actually do the resizing to the rect using the ImageContext stuff
        UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0)
        image.drawInRect(rect)
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return newImage
    }
    
    class func stretchableImage(name: String) -> UIImage {
        return (UIImage(named: name)?.resizableImageWithCapInsets(UIEdgeInsetsMake(0, 0, 0, 0), resizingMode: UIImageResizingMode.Stretch))!
    }
    
    class func base64String(image:UIImage) ->String {
        let imageData = UIImagePNGRepresentation(image);
        return imageData.base64EncodedStringWithOptions( NSDataBase64EncodingOptions.allZeros);
    }
    
    class func fromBase64String(base64:String) ->UIImage{
        if(base64.isEmpty){
            return UIImage(named: "avatar")!;
        }
        
        let data = NSData(base64EncodedString: base64, options: NSDataBase64DecodingOptions.IgnoreUnknownCharacters)!;
        return UIImage(data: data)!;
    }

    class func resizeImage(image: UIImage, maxSize: Int) -> UIImage{
        
        let imageData = UIImagePNGRepresentation(image);
        let imgDataRef = imageData as CFDataRef

        var imageSource = CGImageSourceCreateWithData(imageData, nil)
        
        var options: [String:AnyObject] = [kCGImageSourceThumbnailMaxPixelSize: maxSize, kCGImageSourceCreateThumbnailFromImageIfAbsent: true]
        return UIImage(CGImage: CGImageSourceCreateThumbnailAtIndex(imageSource, 0, options))!
    }
    
    class func retrieveUserImage(userGuid: String, reload: Bool = false) -> UIImage{
        
        let key = "image_" + userGuid
        var base64String:AnyObject? = Utils.getValue(key)
        
        if(base64String == nil || reload){
            var url = "/api/v1/user/\(userGuid)/image"
            var image: UIImage?
            var response = HttpUtils.sendSynchronousRequest(url, method: RequestMethod.GET, requestBody: nil) as NSDictionary
            var imageData = response as NSDictionary
            var imageString = imageData.objectForKey("base64Code") as String
            Utils.saveData(imageString, key: key)
            return self.fromBase64String(imageString)
        }
        
        var imageString = base64String as String
        return self.fromBase64String(imageString)
    }
    
}